package org.duanyu.shopping_order_customer_api.controller;

import com.alibaba.fastjson2.JSON;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.duanyu.shopping_common.pojo.Orders;
import org.duanyu.shopping_common.pojo.Payment;
import org.duanyu.shopping_common.result.BaseResult;
import org.duanyu.shopping_common.service.OrdersService;
import org.duanyu.shopping_common.service.ZfbPayService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/payment")
public class PaymentController {
    @DubboReference
    private ZfbPayService zfbPayService;

    @DubboReference
    private OrdersService ordersService;

    @PostMapping("/pcPay")
    public BaseResult<String> pcPay(String orderId){
        Orders orders = ordersService.findById(orderId);
        String codeUrl= zfbPayService.pcPay(orders);
        return BaseResult.success(codeUrl);
    }

    /**
     * 支付成功的回调方法.用户扫码支付后支付宝调用的
     * @param request 请求对象
     * @return 返回结果
     */
    @PostMapping("/success/notify")
    @GlobalTransactional  //分布式全局事务管理
    public BaseResult successNotify(HttpServletRequest request){
        //1.验签
        Map<String,String[]> parameterMap=new HashMap<>();
        //新map
        Map<String,String[]> newMap=new HashMap<>();
        newMap.putAll(parameterMap);

        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("requestParamMap",newMap);
        zfbPayService.checkSign(paramMap);

        //2.修改订单状态
        String trade_status=request.getParameter("trade_status");
        String out_trade_no=request.getParameter("out_trade_no");

        //如果支付成功
        if (trade_status.equals("TRADE_SUCCESS")){
            //2.修改订单状态
            Orders orders = ordersService.findById(out_trade_no);
            orders.setStatus(2);    //订单状态为已付款
            orders.setPaymentType(2); //支付宝支付
            orders.setPaymentTime(new Date());
            ordersService.update(orders);

            //3.添加交易记录
            Payment payment=new Payment();
            payment.setOrderId(out_trade_no);   //订单编号
            payment.setTransactionId(out_trade_no); //交易号
            payment.setTradeType("支付宝支付");
            payment.setTradeState(trade_status);
            payment.setPayerTotal(orders.getPayment());
            payment.setContent(JSON.toJSONString(request.getParameterMap()));
            payment.setCreateTime(new Date());
            zfbPayService.addPayment(payment);
        }
        return BaseResult.success();
    }
}
